package com.imagecollector.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.imagecollector.common.properties.AliYunOssProperties;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


/**
 * 阿里云oss
 * /**
 *  * <p>
 *  *
 *  * </p>
 *  *
 *  @author ljx
 *  @since 2024-06-21
 *  */

public class AliOSSUtils {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    private AliYunOssProperties aliYunOssProperties;

    public AliYunOssProperties getAliYunOssProperties() {
        return aliYunOssProperties;
    }

    public void setAliYunOssProperties(AliYunOssProperties aliYunOssProperties) {
        this.aliYunOssProperties = aliYunOssProperties;
    }
    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile multipartFile) throws IOException {

        /*获取阿里云OSS参数*/
        endpoint=aliYunOssProperties.getEndpoint();
        accessKeyId=aliYunOssProperties.getAccessKeyId();
        accessKeySecret=aliYunOssProperties.getAccessKeySecret();
        bucketName=aliYunOssProperties.getBucketName();
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        // 避免文件覆盖
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;

        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

    /*删除阿里云OSS云端照片*/
    public void  delete(String url) {
        // 获取阿里云OSS参数
        endpoint=aliYunOssProperties.getEndpoint();
        accessKeyId=aliYunOssProperties.getAccessKeyId();
        accessKeySecret=aliYunOssProperties.getAccessKeySecret();
        bucketName=aliYunOssProperties.getBucketName();
        // 获取文件名
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, fileName);
        // 关闭ossClient
        ossClient.shutdown();
    }
}
